package com.hfh.main.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;

import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import org.springframework.stereotype.Component;

@Component
public class ZhiPuUtil {

    private static final ClientV4 client = new ClientV4.Builder("9fe837c5bf12eb1900b9a1f095bae8bc.380vSYXiis8RDP4J")
            .enableTokenCache()
            .networkConfig(30, 10, 10, 10, TimeUnit.SECONDS)
            .connectionPool(new okhttp3.ConnectionPool(8, 1, TimeUnit.SECONDS))
            .build();


    /**
     * 同步调用
     */
    public static String invoke(String template) {
        System.out.println("model input:" + template);
        String requestIdTemplate = "%s";
        List<ChatMessage> messages = new ArrayList<>();
        ChatMessage chatMessage = new ChatMessage(ChatMessageRole.USER.value(), template);
        messages.add(chatMessage);
        String requestId = String.format(requestIdTemplate, System.currentTimeMillis());
        System.out.println("requestId:" + requestId);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();
        ModelApiResponse invokeModelApiResp = client.invokeModelApi(chatCompletionRequest);
        System.out.println("model output:" + JSONObject.toJSON(invokeModelApiResp));
        return invokeModelApiResp.getData().getChoices().stream().findFirst().get().getMessage().getContent().toString();
    }
}
